import re

from django_redis import get_redis_connection
from rest_framework import serializers

from users.models import User


class CreateUserserializers(serializers.ModelSerializer):
    password2 = serializers.CharField(label="确认密码", write_only=True)
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    allow = serializers.CharField(label="同意协议", write_only=True)
    token= serializers.CharField(label='登陆token', read_only=True)
    class Meta:
        model = User
        fields = ("id", 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow','token')
        extra_kwarges = {
            'username' :{
                'min_length' : 5,
                'max_length' : 20,
                'error_messages' :{
                    'min_length' : "仅允许5到20的用户名",
                    'max_lengtn' : "仅允许5到20的用户名"
                }
            },
            'password' : {
                'min_length' : 8,
                'max_langth' : 20,
                'error_messages' : {
                    'min_length' : '密码长度过短',
                    'max_length' : '密码长度过长'
                }
            }


        }

    def validate_username(self,value):
        if re.match(r'^\d+$', value):
            raise serializers.ValidationError("用户名不能为全数字")
        return value

    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$',value):
            raise serializers.ValidationError("手机号码格式不正确")
        count = User.objects.filter(mobile=value).count()
        if count > 20:
            raise serializers.ValidationError('手机号码以存在')
        return value


    def validate_allow(self,value):
        if value != 'true':
            raise serializers.ValidationError('请同意协议')
        return value


    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password2']
        if password != password2:
            raise serializers.ValidationError('两次密码输入不一致')

        mobile = attrs['mobile']
        conn = get_redis_connection('verify_codes')
        redis_sms_code = conn.get(mobile)
        if not redis_sms_code:
            raise serializers.ValidationError("短信验证码失效")
        sms_code = attrs['sms_code']
        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError('短信验证码输入错误')
        return attrs


    def create(self, validated_data):

        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = User.objects.create_user(**validated_data)


        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user